"""
物流模型
定义物流服务商、物流单和跟踪节点相关的数据库模型
"""
from datetime import datetime
import enum
from app.extensions import db

class LogisticsStatus(enum.Enum):
    """物流状态枚举"""
    PENDING = 'pending'  # 待处理
    PROCESSING = 'processing'  # 处理中
    SHIPPED = 'shipped'  # 已发货
    IN_TRANSIT = 'in_transit'  # 运输中
    DELIVERED = 'delivered'  # 已送达
    FAILED = 'failed'  # 配送失败
    RETURNED = 'returned'  # 已退回

class LogisticsProvider(db.Model):
    """物流服务商模型"""
    __tablename__ = 'logistics_provider'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    description = db.Column(db.Text)
    website = db.Column(db.String(200))
    contact = db.Column(db.String(100))
    is_active = db.Column(db.Boolean, default=True)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关系
    logistics = db.relationship('Logistics', backref='provider', lazy='dynamic')
    
    def __repr__(self):
        return f'<LogisticsProvider {self.name}>'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'website': self.website,
            'contact': self.contact,
            'is_active': self.is_active,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }

class Logistics(db.Model):
    """物流单模型"""
    __tablename__ = 'logistics'
    
    id = db.Column(db.Integer, primary_key=True)
    order_id = db.Column(db.Integer, db.ForeignKey('order.id'), nullable=False, index=True)
    provider_id = db.Column(db.Integer, db.ForeignKey('logistics_provider.id'), nullable=False)
    tracking_number = db.Column(db.String(100), nullable=False, index=True)
    status = db.Column(db.String(20), nullable=False, default=LogisticsStatus.PENDING.value)
    shipping_address = db.Column(db.Text, nullable=False)
    shipping_date = db.Column(db.DateTime)
    delivery_date = db.Column(db.DateTime)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关系
    tracking_nodes = db.relationship('TrackingNode', backref='logistics', lazy='dynamic', 
                                    cascade='all, delete-orphan')
    
    def __repr__(self):
        return f'<Logistics {self.tracking_number}>'
    
    def to_dict(self, include_nodes=False):
        """转换为字典"""
        result = {
            'id': self.id,
            'order_id': self.order_id,
            'provider_id': self.provider_id,
            'provider_name': self.provider.name if self.provider else None,
            'tracking_number': self.tracking_number,
            'status': self.status,
            'shipping_address': self.shipping_address,
            'shipping_date': self.shipping_date.isoformat() if self.shipping_date else None,
            'delivery_date': self.delivery_date.isoformat() if self.delivery_date else None,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }
        
        if include_nodes:
            result['tracking_nodes'] = [node.to_dict() for node in self.tracking_nodes.order_by(TrackingNode.timestamp.desc())]
            
        return result

class TrackingNode(db.Model):
    """物流跟踪节点模型"""
    __tablename__ = 'tracking_node'
    
    id = db.Column(db.Integer, primary_key=True)
    logistics_id = db.Column(db.Integer, db.ForeignKey('logistics.id'), nullable=False, index=True)
    status = db.Column(db.String(20), nullable=False)
    location = db.Column(db.String(200))
    description = db.Column(db.Text)
    timestamp = db.Column(db.DateTime, default=datetime.utcnow)
    
    def __repr__(self):
        return f'<TrackingNode {self.id}>'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'status': self.status,
            'location': self.location,
            'description': self.description,
            'timestamp': self.timestamp.isoformat() if self.timestamp else None
        } 